<template>
  <div class="app-container">
    <div class="cardBox">
      <el-button
        @click="gobackWay"
        type="text"
        icon="el-icon-arrow-left"
        style="color: rgba(0, 0, 0, 0.85)"
        >返回</el-button
      >
      <el-divider direction="vertical"></el-divider>
      <span>{{ title }}</span>
    </div>
    <div class="cardBox marginTop" v-loading="submitLoading">
      <el-row :gutter="20">
        <el-form
          style="width: 900px"
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="110px"
          class="demo-ruleForm"
        >
          <el-col :span="24" class="splitTitle">
            <div class="split">活动信息</div>
          </el-col>
          <el-col :span="12">
            <el-form-item label="活动名称" prop="activity_name">
              <el-input
                placeholder="请输入活动名称"
                v-model="ruleForm.activity_name"
                maxlength="20"
                show-word-limit
                onkeyup="value =value.replace(/[^a-zA-Z0-9\u4e00-\u9fa5]/g, '')"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="ruleForm.status" size="mini">
                <el-radio :label="1">开启</el-radio>
                <el-radio :label="2">关闭</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="活动时间" prop="domeTime">
              <el-date-picker
                v-model="domeTime"
                type="datetimerange"
                value-format="yyyy-MM-dd HH:mm:ss"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              >
              </el-date-picker>
              <el-popover placement="top-start" trigger="hover">
                <p style="font-size: 12px">当前创建的活动开始和结束时间</p>
                <el-button
                  type="text"
                  slot="reference"
                  style="color: #909399; margin: 0 10px"
                  icon="el-icon-info"
                ></el-button>
              </el-popover>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最小值" prop="minimum_product_quantity">
              <el-input
                placeholder="请输入累计商品最小值"
                v-model="ruleForm.minimum_product_quantity"
                maxlength="3"
                show-word-limit
                onkeyup="value=value.replace(/\D/g,'')"
              >
                <template slot="append">
                  <el-popover placement="top-start" trigger="hover">
                    <p style="font-size: 12px">累计购买关联活动商品的最小值</p>
                    <p style="font-size: 12px">
                      该用用户满足最小值和小于最大值可以参与该活动
                    </p>
                    <el-button slot="reference" icon="el-icon-info"></el-button>
                  </el-popover>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最大值" prop="maximum_product_quantity">
              <el-input
                placeholder="请输入累计商品最大值"
                v-model="ruleForm.maximum_product_quantity"
                maxlength="3"
                show-word-limit
                onkeyup="value=value.replace(/\D/g,'')"
              >
                <template slot="append">
                  <el-popover placement="top-start" trigger="hover">
                    <p style="font-size: 12px">累计购买关联活动商品的最大值</p>
                    <p style="font-size: 12px">
                      该用用户满足最小值和小于最大值可以参与该活动
                    </p>
                    <el-button slot="reference" icon="el-icon-info"></el-button>
                  </el-popover>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="转化时间" prop="convertTime">
              <el-date-picker
                v-model="convertTime"
                type="daterange"
                value-format="yyyy-MM-dd"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              >
              </el-date-picker>
              <el-popover placement="top-start" trigger="hover">
                <p style="font-size: 12px">积分向提货券转化的时间段</p>
                <el-button
                  type="text"
                  slot="reference"
                  style="color: #909399; margin: 0 10px"
                  icon="el-icon-info"
                ></el-button>
              </el-popover>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="转化比例" prop="conversion_ratio">
              <el-input
                placeholder="请输入转化比例"
                v-model="ruleForm.conversion_ratio"
                maxlength="3"
                show-word-limit
                onkeyup="value=value.replace(/\D/g,'')"
              >
                <template slot="append">
                  <el-popover placement="top-start" trigger="hover">
                    <p style="font-size: 12px">
                      积分转提货券的转化比例,最大值为100
                    </p>
                    <p style="font-size: 12px">输入100就是100%,50就是50%</p>
                    <el-button slot="reference" icon="el-icon-info"></el-button>
                  </el-popover>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24" class="splitTitle">
            <div class="split">关联活动信息</div>
          </el-col>
          <el-col :span="24">
            <el-form-item label="关联积分活动" prop="activityIds">
              <el-select
                @change="activityIdsChange"
                multiple
                v-model="activityIds"
                style="width: 90%"
                filterable
                remote
                reserve-keyword
                placeholder="关键字查询支持活动ID、活动名称"
                :remote-method="getActivityListWay"
                :loading="activityLoading"
              >
                <el-option
                  v-for="item in activityList"
                  :key="item.id"
                  :label="item.activity_name"
                  :value="item.id"
                />
              </el-select>
              <el-popover placement="top-start" trigger="hover">
                <p style="font-size: 12px">当前转化活动所关联的活动,可多选</p>
                <el-button
                  type="text"
                  slot="reference"
                  style="color: #909399; margin: 0 10px"
                  icon="el-icon-info"
                ></el-button>
              </el-popover>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-for="(item, index) in activityArr" :key="index">
            <div style="font-size: 16px; font-weight: 700">
              {{ item.name
              }}<span style="font-size: 14px"
                >(活动ID:{{ item.linked_bonus_activity_id }})</span
              >
            </div>
            <el-col :span="12">
              <el-form-item label="每日转化时间">
                <el-time-picker
                  @change="elTimePicker"
                  value-format="HH:mm:ss"
                  v-model="item.conversion_time"
                  placeholder="任意时间点"
                >
                </el-time-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="第几天开始转化">
                <el-input
                  placeholder="请输入第几天开始转化"
                  v-model="item.days"
                  maxlength="3"
                  show-word-limit
                  onkeyup="value=value.replace(/\D/g,'')"
                >
                </el-input>
              </el-form-item>
            </el-col>
          </el-col>
          <el-col class="marginTop" style="text-align: center">
            <el-button size="small" type="primary" @click="resettingWay"
              >重置</el-button
            >
            <el-button size="small" type="primary" @click="submitWay"
              >提交</el-button
            >
          </el-col>
        </el-form>
      </el-row>
    </div>
  </div>
</template>

<script>
import {
  addConversion,
  editConversion,
  getBonusList,
  getConversionDetail,
} from "@/api/activity/agriculture";
import { getActivityGoodsList } from "@/api/index";
export default {
  data() {
    return {
      title: "",
      submitLoading: false,
      disabledGoods: true,
      ruleForm: {
        activity_name: "",
        start_time: "",
        end_time: "",
        status: 2,
        minimum_product_quantity: "",
        maximum_product_quantity: "",
        start_days: "",
        end_days: "",
        conversion_ratio: "",
        conversion: [],
      },
      // 时间段回显
      domeTime: [],
      // 转换时间
      convertTime: [],
      // 活动商品回显
      activityIds: [],
      // 当前已经选中的关联活动
      activityArr: [],
      activitySaerch: {
        keywords: "",
        page: 1,
        count: 20,
      },
      activityList: [],
      activityLoading: false,
      rules: {
        activity_name: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                return callback(new Error("请输入活动名称"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        domeTime: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (this.domeTime.length == 0) {
                return callback(new Error("请选择活动时间"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        minimum_product_quantity: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                return callback(new Error("请输入累计商品最小值"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        maximum_product_quantity: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                return callback(new Error("请输入累计商品最大值"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        convertTime: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (this.convertTime.length == 0) {
                return callback(new Error("请选择转化时间"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        conversion_ratio: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                return callback(new Error("请输入转换比例"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        activityIds: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (this.activityIds.length == 0) {
                return callback(new Error("请选择关联的活动"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    if (this.$route.query.id) {
      this.title = "修改活动";
      getConversionDetail({ id: this.$route.query.id }).then((res) => {
        this.ruleForm.id = res.data.id;
        this.ruleForm.activity_name = res.data.activity_name;
        this.ruleForm.status = res.data.status;
        this.ruleForm.minimum_product_quantity =
          res.data.minimum_product_quantity;
        this.ruleForm.maximum_product_quantity =
          res.data.maximum_product_quantity;
        this.ruleForm.conversion_ratio = res.data.conversion_ratio;
        this.domeTime = [res.data.start_time, res.data.end_time];
        this.convertTime = [res.data.start_days, res.data.end_days];
        this.activityList = res.data.bonus;
        res.data.conversion.forEach((item) => {
          this.activityIds.push(item.linked_bonus_activity_id);
          this.activityArr.push({
            name: item.activity_name,
            linked_bonus_activity_id: item.linked_bonus_activity_id,
            conversion_time: item.conversion_time,
            days: item.days,
          });
        });
      });
    } else {
      this.title = "添加活动";
    }
  },
  methods: {
    getActivityListWay(query) {
      this.activityLoading = true;
      if (query !== "") {
        this.activitySaerch.keywords = query;
      }
      getBonusList(this.activitySaerch)
        .then((res) => {
          this.activityLoading = false;
          this.activityList = res.data.list;
        })
        .catch((err) => {
          this.$messages.error(err.msg);
          this.activityLoading = false;
        });
    },
    activityIdsChange(val) {
      var arr = [];
      this.activityList.forEach((item, index) => {
        val.forEach((element, indexs) => {
          if (item.id == element) {
            arr.push({
              name: item.activity_name,
              linked_bonus_activity_id: item.id,
              conversion_time: "",
              days: "",
            });
          }
        });
      });
      if (val.length > this.activityArr.length) {
        if (this.activityArr.length == 0) {
          this.activityArr = arr;
        }
        var arr1 = [];
        // 遍历第一个数组
        for (let i = 0; i < arr.length; i++) {
          // 判断当前元素在第二个数组中是否存在
          if (
            !this.activityArr.some(
              (item) =>
                item.linked_bonus_activity_id ===
                arr[i].linked_bonus_activity_id
            )
          ) {
            // 如果不存在则将其添加到结果数组中
            arr1.push(arr[i]);
          }
        }
        if (arr1.length !== 0) {
          this.activityArr.push(...arr1);
        }
      } else {
        var arr1 = [];
        // 遍历第一个数组
        for (let i = 0; i < this.activityArr.length; i++) {
          // 判断当前元素在第二个数组中是否存在
          if (
            arr.some(
              (item) =>
                item.linked_bonus_activity_id ==
                this.activityArr[i].linked_bonus_activity_id
            )
          ) {
            // 如果不存在则将其添加到结果数组中
            arr1.push(this.activityArr[i]);
          }
        }
        this.activityArr = arr1;
      }
    },
    resettingWay() {
      this.ruleForm = {
        activity_name: "",
        start_time: "",
        end_time: "",
        status: 2,
        minimum_product_quantity: "",
        maximum_product_quantity: "",
        start_days: "",
        end_days: "",
        conversion_ratio: "",
        conversion: [],
      };
      this.activityIds = [];
      this.activityArr = [];
      this.$refs.ruleForm.resetFields();
    },
    submitWay() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          var through = this.activityArr.some((item, index) => {
            if (!item.conversion_time) {
              this.$messages.error("请选择" + item.name + "下每日转化时间");
              return true;
            }
            if (!item.days) {
              this.$messages.error("请输入" + item.name + "下第几天开始转化");
              return true;
            }
          });
          if (!through) {
            this.ruleForm.start_time = this.domeTime[0];
            this.ruleForm.end_time = this.domeTime[1];
            this.ruleForm.start_days = this.convertTime[0];
            this.ruleForm.end_days = this.convertTime[1];
            this.ruleForm.conversion = [...this.activityArr];
            console.log(this.ruleForm);
            // return;
            if (!this.ruleForm.id) {
              this.submitLoading = true;
              addConversion(this.ruleForm)
                .then((res) => {
                  this.submitLoading = false;
                  this.$messages.success("添加成功");
                  this.resettingWay();
                  this.gobackWay();
                })
                .catch((err) => {
                  this.$messages.error(err.msg);
                  this.submitLoading = false;
                });
            } else {
              this.submitLoading = true;
              editConversion(this.ruleForm)
                .then((res) => {
                  this.submitLoading = false;
                  this.$messages.success("修改成功");
                  this.resettingWay();
                  this.gobackWay();
                })
                .catch((err) => {
                  this.$messages.error(err.msg);
                  this.submitLoading = false;
                });
            }
          }
        }
      });
    },
    elTimePicker(time) {},
    gobackWay() {
      this.$router.go(-1);
    },
  },
};
</script>

<style></style>
